#_*_ coding: UTF-8 _*_

import sys
from PyQt4 import QtCore, QtGui
from core import uicomponents,log

class MainView(QtGui.QFrame):
	def __init__(self, parent=None):
		QtGui.QBoxLayout.__init__(self, parent)

		self.setFrameShape(QtGui.QFrame.StyledPanel)
		self.setFrameStyle(QtGui.QFrame.Raised)

class NiceTextEdit(QtGui.QTextEdit):
	def __init__(self, fragmentStart='(', fragmentEnd=')', delimiter=[' '], parent=None):
		QtGui.QTextEdit.__init__(self, parent)

		self.fragStart = fragmentStart
		self.fragEnd = fragmentEnd
		self.delim = delimiter

	def cursorForPosition(self, pos):
		raise Exception('Abolfazl: never call this function!')
	
	def setTextCursor(self, cursor):
		if type(cursor) is not NiceTextCursor:
			raise Exception('Abolfazl: only NiceTextCursor should be used with NiceTextEdit!')
		QtGui.QTextEdit.setTextCursor(self, cursor)
		
	def textCursor(self):
		cursor = QtGui.QTextEdit.textCursor(self)
		return NiceTextCursor(cursor, self.fragStart, self.fragEnd, self.delim)

	def keyPressEvent(self, e):
		keycodes = {16777235:"prevAye()",
				16777237:"nextAye()",
				16777234:"nextWord()",
				16777236:"prevWord()",
				16777239:"nextPage()",
				16777238:"prevPage()"}
		if e.key() in keycodes:
			log.logger.debug("navigation keys pressed:%d %s" % (e.key(),keycodes[e.key()]))
			self.emit(QtCore.SIGNAL(keycodes[e.key()]))
		else:
			e.ignore()
		
class NiceTextCursor(QtGui.QTextCursor):
	def __init__(self, document_frame_block_cursor, fragmentStart, fragmentEnd, delimiter):
		QtGui.QTextCursor.__init__(self, document_frame_block_cursor)

		self.fragStart = fragmentStart
		self.fragEnd = fragmentEnd
		self.delim = delimiter

	def __reverseFind(self, str, char, idx, delim):
		if idx<0:
			return 0, -1
		if idx>=len(str):
			return 0,-1
		
		wordIdx = 0
		inDelim = str[idx] in delim
	
		while idx>=0 and str[idx]!=char:
			if str[idx] == "]" :
				idx = idx - 1
				while str[idx]!="[":
					idx = idx - 1
				idx = idx - 1

			if str[idx] == "}" :
				idx = idx - 1
				while str[idx]!="{":
					idx = idx - 1
				idx = idx - 1

			if str[idx] in ["{","["]:
				idx = idx - 1
				wordIdx = -1

			if inDelim != (str[idx] in delim):
				inDelim = not inDelim
				wordIdx = wordIdx + 1
			idx = idx-1

		if inDelim:
			return max(0, (wordIdx-1)/2), idx
		else:
			return wordIdx/2, idx
	
	def __reverseCount(self,text,idx):
		last = 0
		t = unicode(text)
		idx = t.find(")",idx) + 1
		t = t[:idx]
		nidx = t.rfind(")")
		lnum = 10000
		result = 0
		while nidx>-1:
			mnum = t[:nidx+1].rfind("(")+1
			num = int(t[mnum:nidx])
			print num,
			if num>lnum:
				result += 1
				if last == 1:
					last = -1
			t = t[:mnum]
			nidx = t.rfind(")")
			lnum = num
			if last != -1 :
				last += 1
		print 
		return (result,last)
	

	def __positionFragmentLabelAndWordOffset(self, position):
		"""Returns [fragment, word_index]"""
		curBlock = self.block()
		text = curBlock.text()
		charIdx = position-curBlock.position()
		sureIndex,isLast = self.__reverseCount(text,charIdx)

		wordIdx, edIdx = self.__reverseFind(text, self.fragEnd, charIdx, self.delim)
		if isLast==-1:
			return sureIndex,u'0',wordIdx
		if edIdx==-1:
			if sureIndex>0:
				return sureIndex-1,u'0',wordIdx
			else:
				return 0,u'', wordIdx
		x, stIdx = self.__reverseFind(text, self.fragStart, edIdx-1, self.delim)

		return [sureIndex,unicode(text[stIdx+1:edIdx].trimmed()), wordIdx]
		
	def selectionFragmentLabelAndWordOffset(self):
		start = min(self.position(), self.anchor())
		end = max(self.position(), self.anchor())
		end = max(end-1, start)

		position = self.__positionFragmentLabelAndWordOffset(end)
	

		if self.hasSelection():
			anchor = self.__positionFragmentLabelAndWordOffset(start)

			#curBlock = self.block()
			#if position[1]>anchor[1] and curBlock.text()[start-curBlock.position()] in self.delim:
				#anchor[1] = anchor[1]+1
			return position, anchor
		else:
			return position, position

